package com.cz.run.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.cz.run.beans.base.PageDTO;
import com.cz.run.beans.base.ReturnDTO;
import com.cz.run.beans.mysql.*;
import com.cz.run.beans.po.sport.PutStopNumPO;
import com.cz.run.beans.vo.sport.ForceVO;
import com.cz.run.beans.vo.sport.RankingsVO;
import com.cz.run.beans.vo.user.ShcVO;
import com.cz.run.constants.ConstantKey;
import com.cz.run.service.*;
import com.cz.run.utils.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Description: TODO()
 * @auther:CAIYJ
 * @Date:2018/5/27 21:34
 */
@Api(value = "运动模块")
@RestController
@RequestMapping(value = "/sport")
public class SportServer {

    @Autowired
    private IForceStatisticsService forceStatisticsService;

    @Autowired
    private IUserForceService userForceService;

    @Autowired
    private IUserPointService userPointService;

    @Autowired
    private IUserForceDynamicService userForceDynamicService;

    @Autowired
    private IUserForceCoefficientService iUserForceCoefficientService;

    @Autowired
    private IUserBaseService userBaseService;

    @ApiOperation(value = "排行榜", notes = "排行榜", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = "/rankings")
    public ReturnDTO<PageDTO<RankingsVO>> rankings(@RequestBody PageDTO pageDTO, HttpServletRequest request) throws Exception {
        EntityWrapper<UserForceDynamic> ew = new EntityWrapper<>();
        ew.where("time = {0}", DateUtil.getDateAfterDayYYYYMMDD(new Date(), -1));
        ew.orderBy("step", false);
        Page<UserForceDynamic> page = new Page<>(pageDTO.getCurrentPage(), pageDTO.getPageSize());
        page = userForceDynamicService.selectPage(page, ew);
        List<UserForceDynamic> UserForceDynamics = userForceDynamicService.selectList(ew);
        List<RankingsVO> list = new ArrayList<>();
        RankingsVO vo = null;
        if (pageDTO.getCurrentPage() == 1) {
            String userId = (String) request.getAttribute(ConstantKey.USER_KEY);
            UserBase userBase = userBaseService.selectById(userId);
            if(null!=userBase&&0==userBase.getStatus()){
                return ReturnDTO.fail("账户被封禁，请联系客服");
            }
            if (userBase != null) {
                vo = new RankingsVO();
                vo.setName(userBase.getNickName());
                vo.setSort(1);
                EntityWrapper<UserForceDynamic> uf = new EntityWrapper<>();
                uf.where("user_id = {0}", userId);
                uf.and("time = {0}", DateUtil.getDateAfterDayYYYYMMDD(new Date(), -1));
                UserForceDynamic userForceDynamic = userForceDynamicService.selectOne(uf);
                if (userForceDynamic != null) {
                    vo.setStepNumber(userForceDynamic.getStep().toString());
                }
                int count = 1;
                boolean flag =false;
                        ok:for(UserForceDynamic param:UserForceDynamics){
                            if(param.getUserId().equals(userId)){
                                vo.setSort(count);
                                break ok;
                            }
                            if(count>100){
                                vo.setSort(100);
                                break ok;
                            }
                            count= count+1;

                        }
                list.add(vo);
            }
        }
        if (page != null && page.getRecords() != null && page.getRecords().size() > 0) {
            Set<Integer> ids = new HashSet<>();
            for (UserForceDynamic userForceDynamic : page.getRecords()) {
                ids.add(userForceDynamic.getUserId());
            }
            int sort = 0;
            if (pageDTO.getCurrentPage() >= 1) {
                sort = (pageDTO.getCurrentPage() - 1) * pageDTO.getPageSize() + 1;
            }
            List<UserBase> bases = userBaseService.selectBatchIds(ids);
            for (UserForceDynamic userForceDynamic : page.getRecords()) {
                vo = new RankingsVO();
                vo.setStepNumber(userForceDynamic.getStep().toString());
                vo.setSort(sort);
                sort++;
                for (UserBase base : bases) {
                    if (userForceDynamic.getUserId().equals(base.getId())) {
                        vo.setName(base.getNickName());
                        break;
                    }
                }
                list.add(vo);
            }
            pageDTO.setContent(list);
            pageDTO.setTotalRecord(page.getTotal());
        }
        return ReturnDTO.success(pageDTO);
    }

    @ApiOperation(value = "全网算力统计", notes = "全网算力统计", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = "/force")
    public ReturnDTO<ForceVO> force(HttpServletRequest request) throws Exception {
String userId =(String) request.getAttribute(ConstantKey.USER_KEY);
        EntityWrapper<UserForce> ew1 = new EntityWrapper<>();
        ew1.where("user_id = {0}",  userId);
        UserForce userForce =userForceService.selectOne(ew1);
        EntityWrapper<ForceStatistics> ew = new EntityWrapper<>();
        ew.where("time = {0}", DateUtil.getDateAfterDayYYYYMMDD(new Date(), -1));
        List<ForceStatistics> list = forceStatisticsService.selectList(ew);
        ForceVO vo = new ForceVO();
        if (null != list && list.size() > 0) {
            vo.setNick(userForce.getLevel());
            vo.setAvgForce(list.get(0).getForceAvg());
            vo.setForce(list.get(0).getPoolTotal());
            vo.setMaxForce(list.get(0).getForceMax());
            vo.setMinForce(list.get(0).getForceMin());
            vo.setTotalForce(list.get(0).getForceTotal());
            vo.setYield(list.get(0).getPoolTotal());
            vo.setMaxGetForce(list.get(0).getPointMax());
        }
        return ReturnDTO.success(vo);
    }

    @ApiOperation(value = "我的区块信息", notes = "我的区块信息", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = "point")
    public ReturnDTO<ShcVO> shc(HttpServletRequest request) throws Exception {
        String userId = (String) request.getAttribute(ConstantKey.USER_KEY);
        ShcVO vo = new ShcVO();
        EntityWrapper<UserForce> few = new EntityWrapper<>();
        few.where("user_id = {0}", userId);
        UserForce userForce = userForceService.selectOne(few);
        EntityWrapper<UserForceCoefficient> fcew = new EntityWrapper<>();
        fcew.where("user_id = {0}", userId);
        UserForceCoefficient userForceCoefficient =iUserForceCoefficientService.selectOne(fcew);


        EntityWrapper<UserForceDynamic> doew = new EntityWrapper<>();
        doew.where("user_id = {0}", userId);
        doew.and("time = {0}", DateUtil.getDateAfterDayYYYYMMDD(new Date(), 0));

      UserForceDynamic userForceDynamic = userForceDynamicService.selectOne(doew);
        if (null != userForce) {
            vo.setMyShc(userForceCoefficient.getBaseForce()+(null==userForceDynamic?0:userForceDynamic.getTemp()));
        }
        EntityWrapper<UserPoint> pew = new EntityWrapper<>();
        pew.where("user_id = {0}", userId);
        UserPoint point = userPointService.selectOne(pew);
        if (null != point) {
            vo.setShc(point.getPoint());
        }
        return ReturnDTO.success(vo);
    }

    @ApiOperation(value = "更新步数", notes = "更新步数", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = "putStopNum")
    public ReturnDTO<String> putStopNum(@RequestBody PutStopNumPO po, HttpServletRequest request) throws Exception {
        String userId = (String) request.getAttribute(ConstantKey.USER_KEY);
        EntityWrapper<UserForceDynamic> uf = new EntityWrapper<>();
        uf.where("user_id = {0}", userId);
        uf.and("time = {0}", DateUtil.getDateAfterDayYYYYMMDD(new Date(), 0));
        UserForceDynamic userForceDynamic = userForceDynamicService.selectOne(uf);
        if (userForceDynamic != null) {
            userForceDynamic.setStep(po.getNum());
            userForceDynamicService.updateById(userForceDynamic);
        } else {
            userForceDynamic = new UserForceDynamic();
            userForceDynamic.setStep(po.getNum());
            userForceDynamic.setTime(new Date());
            userForceDynamic.setUserId(Integer.parseInt(userId));
            userForceDynamicService.insert(userForceDynamic);
        }
        return ReturnDTO.success("成功");
    }
}
